package com.genius.adminmanager.user.service.impl;

import java.sql.SQLException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.genius.adminmanager.other.entity.ResponseJson;
import com.genius.adminmanager.user.entity.UserJson;
import com.genius.adminmanager.user.service.UserServiceAdapter;
import com.genius.workflow.page.PageResult;
import com.genius.workflow.page.SqlLang;
import com.genius.workflow.util.ConnectionException;
import com.genius.workflow.util.DBClosedException;
import com.genius.workflow.util.DBTools;
import com.genius.workflow.util.DBTools2;
import com.genius.workflow.util.PasswordMD5;
import com.genius.workflow.util.Pattern;
import com.genius.workflow.util.TimeDiff;

@Service("userInsertService")
public class UserInsertServiceImpl extends UserServiceAdapter{

	@Override
	public JSONObject add(JSONObject json, JSONObject response) {
//		String pwd = StringUtils.trim(json.getString(UserJson.password));
		String pwd = "123456";
    	String username = StringUtils.trim(json.getString(UserJson.username));

    	String status = json.containsKey(UserJson.status)?"1":"0";
    	String createTime = TimeDiff.getNowTime(Pattern.yyyy_MM_dd_HH_mm_ss);
    	json.put(UserJson.createTime, createTime);
    	json.put(UserJson.status, status);
    	json.put(UserJson.userId, "0");
    	json.put(UserJson.password, PasswordMD5.MD5Pwd(username, pwd));
    	// 先查询主键是否存在
    	try {
    		String keywords = UserJson.username;
    		String table = "t_user";
			JSONObject userJson = DBTools.getIsExist(keywords, table, json);
			
			if(userJson != null){
				response.put(ResponseJson.msg, "已存在该用户名");
				response.put(ResponseJson.status, ResponseJson.status_Failed);
				return response;
			}
			String insertField = UserJson.userId+","+UserJson.username+","+UserJson.password+","+UserJson.command+","+UserJson.name
					+","+UserJson.sex+","+UserJson.phone+","+UserJson.mail+","+UserJson.createTime+","
					+UserJson.status+","+UserJson.groupId+","+UserJson.jobnumber+","+UserJson.remark+","+UserJson.company;
			DBTools.insert(insertField, table,json);
			response.put(ResponseJson.status, ResponseJson.status_Success);
			response.put(ResponseJson.msg, ResponseJson.msg_Add_Data_Success);
		}  catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_No_Porwer_Query_Field);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Add_Data_Error);
		}
		return response;
	}
	@Override
	public JSONObject batchadd(JSONObject json1, JSONObject response) {
		JSONArray insertary = new JSONArray();
		JSONArray updateary = new JSONArray();
		JSONArray roleary = new JSONArray();
		String pwd = "123456";
        String status = "1";
    	String createTime = TimeDiff.getNowTime(Pattern.yyyy_MM_dd_HH_mm_ss);
    	JSONArray json = json1.getJSONArray("user");
      //JSONArray jsonrole = json1.getJSONArray("user");
		String selectSB = "select `value` from idmax where  `key`= 'user' ";
		SqlLang sql = DBTools2.getSelectPageSql(null,selectSB,1,1,null,null,null);
		JSONObject mergeJson = new JSONObject();
		String parameterArr [] = DBTools2.parsePermeterBySql(sql.getSourceSql(), mergeJson);
		PageResult result;
    	// 先查询主键是否存在
    	try {
    		result = DBTools2.selectByCount(sql,parameterArr);
			JSONArray data = (JSONArray)result.getData();
			int idmax = data.getJSONObject(0).getInteger("value");
    		String table = "t_user";
    		boolean tof= true;
    		for(int i=0;i<json.size();i++) {			
    			JSONObject usjson =  json.getJSONObject(i);
    			String selectSB1 = "select userId,username,jobnumber from t_user where username= '"+usjson.getString("username")+"' ";
    			SqlLang sql1 = DBTools2.getSelectPageSql(null,selectSB1,1,10,null,null,null);
    			String parameterArr1 [] = DBTools2.parsePermeterBySql(sql1.getSourceSql(), mergeJson);
    			PageResult result1=DBTools2.selectByCount(sql1,parameterArr1);
    			JSONArray data1 = (JSONArray)result1.getData();
    			if(data1.size()==1) {
    				if(data1.getJSONObject(0).getString("jobnumber") ==null ) {data1.getJSONObject(0).put("jobnumber", "");}
    				String[] jobnum  = data1.getJSONObject(0).getString("jobnumber").split(",");   //查询出的工号
    				String[] jobnum1  = usjson.getString("jobnumber").split(",");  //接口的工号
    				String jobnumberString  = data1.getJSONObject(0).getString("jobnumber");
    				String userIdString  = data1.getJSONObject(0).getString("userId");
    				String roleIdString  = usjson.getString("roleId");
    				for(int ss =0;ss<jobnum1.length;ss++) {
    					tof=true;
    					String num = jobnum1[ss];//3775 1005
    					for(int sss =0;sss<jobnum.length;sss++) {//1006 1005
    						if(num.equals(jobnum[sss])){
    							tof=false;
    						}
    					}
    					if(tof){
    						if(!num.equals("")) {
	    							if(jobnumberString.equals("")) {
	    								jobnumberString= jobnumberString+num;
	    							}else {
	    								jobnumberString= jobnumberString+","+num;
	    							}
    						}
    						//break;
    					}
    				}
    				usjson.put("jobnumber",jobnumberString);
    				usjson.put("userId",userIdString);
    				
    				//usjson
    				String selectSB2 = "select * from t_user_role where userId = '"+userIdString+"' and roleId = '"+roleIdString+"'";
        			SqlLang sql2 = DBTools2.getSelectPageSql(null,selectSB2,1,10,null,null,null);
        			String parameterArr2 [] = DBTools2.parsePermeterBySql(sql2.getSourceSql(), mergeJson);
        			PageResult result2=DBTools2.selectByCount(sql2,parameterArr2);
        			JSONArray data2 = (JSONArray)result2.getData();
        			if(data2.size() == 0) {
        				roleary.add(usjson);
        			}
    				updateary.add(usjson);
    			}else if(data1.size()>1) {
        				response.put(ResponseJson.msg, "录入错误");
        				response.put(ResponseJson.status, ResponseJson.status_Failed);
        				return response;
    			}else {
        			usjson.put(UserJson.password, PasswordMD5.MD5Pwd(StringUtils.trim(usjson.getString(UserJson.username)), pwd));
        			usjson.put(UserJson.createTime, createTime);
        			usjson.put(UserJson.status, status);
        			usjson.put(UserJson.command, "123");
        			usjson.put(UserJson.company, "shoudongtianjia");
        			usjson.put(UserJson.userId,idmax);
        			idmax +=1;
    				insertary.add(usjson);
    				roleary.add(usjson);
    			} 
    		}
			String insertField = UserJson.userId+","+UserJson.username+","+UserJson.password+","+UserJson.command+","+UserJson.name
					+","+UserJson.sex+","+UserJson.phone+","+UserJson.mail+","+UserJson.createTime+","
					+UserJson.status+","+UserJson.groupId+","+UserJson.jobnumber+","+UserJson.remark+","+UserJson.company;
			DBTools.insertBatch(insertField, table,insertary);
			String insertField1 = "roleId,userId";
			DBTools.insertBatch(insertField1, "t_user_role",roleary);
			DBTools.updateBatch("jobnumber", "userId", "t_user", updateary);
			/*System.err.println("insertary>"+insertary);
			System.err.println("updateary>"+updateary);
			System.err.println("roleary>"+roleary);*/
			response.put(ResponseJson.status, ResponseJson.status_Success);
			response.put(ResponseJson.msg, ResponseJson.msg_Add_Data_Success);
		}  catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_No_Porwer_Query_Field);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Add_Data_Error);
		}
		return response;
	}
	 
	
	
}
